03. While Loops
While Loops
While loops
while
loops allow you to repeat an if
condition over and over for as long as that condition remains true
, hence the name while
!
To create a while
loop, simply follow the same steps like an if
condition, but replace the if
with a while
to look something like this:
while(isRaining){
System.out.println("It's still raining outside!");
isRaining = checkWeather();
}
System.out.println("Now it's not raining anymore");
This code block above will continue to print the message "It's still raining outside!"
for as long as the boolean isRaining
is true, once the function checkWeather()
returns false isRaining
will no longer be true, so the while loop would end and the message "Now it's not raining anymore"
will be displayed.
Unlike if
blocks however, while
loops don't have else
blocks, they are simply like a repeated if
block that would only end when the condition becomes false.